"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addSvgs = void 0;
const templates_1 = require("./templates");
const tools_1 = require("./tools");
const fs = require("fs");
const path = require("path");
function addSvgs(options) {
    const { add, inputValue } = options;
    if (typeof add !== "string") {
        throw new Error("add must be a string");
    }
    if (typeof inputValue !== "string") {
        throw new Error("input must be a string");
    }
    if (!inputValue.endsWith(".js")) {
        throw new Error("input must be a .js file");
    }
    const inputPathList = (inputValue || "").split("/").filter(Boolean);
    const inputPath = path.join(process.cwd(), ...inputPathList);
    if (!fs.existsSync(inputPath) || !fs.statSync(inputPath).isFile()) {
        throw new Error(`Input path ${inputPath} does not exist or is not a file`);
    }
    const { svgId, svgList: oldSvgList } = (0, tools_1.getIconfontContent)(inputPath);
    const newSvgList = addNewSvgs(options);
    const svgMap = oldSvgList.reduce((prev, cur) => {
        prev[cur.name] = cur;
        return prev;
    }, {});
    newSvgList.forEach((svg) => {
        const { name } = svg;
        if (svgMap[name]) {
            svg.name = findNoRepeatName(svgMap, svg.name);
        }
        svgMap[svg.name] = svg;
    });
    const svgList = Object.keys(svgMap).map((name) => svgMap[name]);
    outputFile(svgId, svgList, options);
}
exports.addSvgs = addSvgs;
function findNoRepeatName(svgMap, name) {
    let nName = name;
    while (svgMap[nName]) {
        nName = `${nName}-1`;
    }
    return nName;
}
// 读取要添加的svg文件
function addNewSvgs(options) {
    const { add, isPure, isDeep } = options;
    let svgList = [];
    const addPathList = (add || "").split("/").filter(Boolean);
    const addPath = path.join(process.cwd(), ...addPathList);
    if (!fs.existsSync(addPath)) {
        throw new Error(`add path ${addPath} not exist`);
    }
    if (fs.statSync(addPath).isFile()) {
        if (!add?.endsWith(".svg")) {
            throw new Error("add must be a svg file");
        }
    }
    svgList = (0, tools_1.readSvgFiles)(addPath, { isDeep, isPure });
    return svgList;
}
// 输出iconfont.js文件
function outputFile(svgId, svgList, options) {
    const { outputValue, inputValue } = options;
    let out = outputValue;
    // 如果没有指定output文件就直接修改源文件目录
    if (!out) {
        out = inputValue;
    }
    const outputPath = (0, tools_1.getOutputPath)(out, "iconfont.js", ".js");
    const content = (0, templates_1.generateIconfontContent)(svgList.map(templates_1.generateSymbolContnt).join(""), svgId);
    fs.writeFileSync(outputPath, content);
    const html = (0, templates_1.generateHtmlContent)(svgList.map((item) => item.name));
    const htmlPath = path.join(path.parse(outputPath).dir, "index.html");
    fs.writeFileSync(htmlPath, html);
}
